package com.five.zhh.fiveinfive.schedule;


import cn.hutool.core.collection.CollUtil;
import com.five.zhh.fiveinfive.room.GameRoom;
import com.five.zhh.fiveinfive.room.GameRoomManager;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class GameRoomSchedule {

    /**
     * 每隔五分钟清除掉没有玩家的房间
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void clearRoom() {
        Map<String, GameRoom> rooms = GameRoomManager.getGameRooms();
        if (CollUtil.isEmpty(rooms)) {
            return;
        }
        // 五分钟
        final long closeStandard = 5 * 60 * 1000;
        List<String> roomCodes = new ArrayList<>(rooms.keySet());
        for (String roomCode : roomCodes) {
            GameRoom room = rooms.get(roomCode);
            long createTimestamp = room.getCreateTimestamp();
            if (System.currentTimeMillis() - createTimestamp <= closeStandard) {
                continue;
            }
            if (CollUtil.isEmpty(room.getPlayers())) {
                GameRoomManager.removeGameRoom(roomCode);
            }
        }
    }

}
